// pages/product/unit-detail/unit-detail.js
import ProductService from "../../../class/service/ProductService";
import SmsService from "../../../class/service/SmsService";
import Router from "../../../class/Router";
import Tips from "../../../utils/Tips";

const util = require("../../../utils/util.js")
const storage = require("../../../utils/storage.js")
const constant = require("../../../constant.js")
const notification = require("../../../utils/WxNotificationCenter.js");

const productService = new ProductService();
const smsService = new SmsService();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    init: false,
    playStatus: [true, false, false],
    tab: 'task',
    needMobile: false,
    codeMsg: '获取验证码'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    var that = this;
    that.setData({ unitId: options.id})
    that.setData({ productId: options.productId })

    var unionid = wx.getStorageSync(storage.keys.unionid);
    that.setData({
      unionid: unionid
    })

    var system = wx.getStorageSync(storage.keys.system);
    that.setData({
      system:system
    })

    var openid = wx.getStorageSync(storage.keys.openid);
    that.setData({
      openid: openid
    })

    var mobile = wx.getStorageSync(storage.keys.mobile);
    that.setData({
      mobile: mobile
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    
    if (that.data.mobile) {
      that.initData()
    } else {
      that.setData({
        init: false,
        needMobile: true
      })
    }

    
  },

  initData: function() {
    var that = this;
    Tips.loading();
    productService.unitDetail(that.data.productId, that.data.unitId).then(data => {
      that.initMaterial(data.materials);
      Tips.loaded();
      that.setData({
        "init": true,
        "course": data.course,
        "answer": data.answer,
        "exam": data.exam,
        "courseUnit": data.courseUnit,
        "materials": data.materials
      })

    }, res => {
      Tips.error("获取练习失败");
      that.setData({
        "init": true
      })
    })
  },

  onInputPhone: function (e) {
    var that = this;
    that.setData({
      phone: e.detail
    })
  },

  inputCode: function (e) {
    var that = this;
    that.setData({
      code: e.detail
    })
    if (that.data.code.length == 6) {
      that.bindUser();
    }
  },

  bindUser: function () {
    var that = this;

    smsService.bindUser(that.data.unionid, that.data.phone, that.data.code, that.data.token, that.data.openid).then(data => {
      that.setData({
        mobile: data.user.mobile
      })
      wx.setStorageSync(storage.keys.mobile, that.data.mobile)
      that.setData({
        init: false,
        needMobile: false
      })
      that.initData();
    }, res => {
      Tips.error("绑定验证码失败");
      that.setData({
        disableGetCode: false,
        codeMsg: "获取验证码"
      })
    })
  },

  validMobile: function () {
    var that = this;
    if (!that.data.phone) {
      that.showMessage("请先输入手机")
      return false;
    } else if (!/^((13)|(14)|(15)|(16)|(17)|(18)|(19))\d{9}$/.test(that.data.phone)) {
      that.showMessage("请输入正确的手机")
      return false;
    }

    return true;
  },

  onSendSms: function (event) {

    var that = this;
    if (that.validMobile()) {

      that.setData({
        disableGetCode: true
      })

      var seconds = 60;
      var interval = setInterval(function (e) {
        seconds--;
        if (seconds < 0) {
          that.setData({
            disableGetCode: false,
            codeMsg: "重新获取验证码"
          })
          clearInterval(interval);
        } else {
          that.setData({
            codeMsg: "发送中（" + seconds + "）秒"
          })
        }
      }, 1000)

      smsService.send(that.data.phone).then(data => {
        that.setData({
          token: data.token
        })
        Tips.loaded();
      }, res => {
        Tips.error("获取验证码失败");
        that.setData({
          disableGetCode: false,
          codeMsg: "获取验证码"
        })
        clearInterval(interval);
      });
    }
  },

  showMessage: function (text) {
    var that = this
    that.setData({
      showMessage: true,
      messageContent: text
    })
    setTimeout(function () {
      that.setData({
        showMessage: false,
        messageContent: ''
      })
    }, 3000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 标签切换页面
   */
  switchTap: function (e) {
    var that = this;
    var tab = e.currentTarget.dataset.tab;
    console.log(tab)
    that.setData({
      tab: tab
    })
  },

  initMaterial: function(materials) {
    var that = this;
    var vedio = [];
    var tasks = [];

    for (var i in materials) {
      if (materials[i].type == 'BOOK_COACH') {
        vedio.push(materials[i]);
      } else if (materials[i].type == 'BOOK_ANSWER') {
        tasks.push(materials[i]);
      }
    }

    console.log(tasks)
    var playStatus = []
    for (var i in vedio) {
      if(i==0) {
        playStatus.push(true)
      } else {
        playStatus.push(false)
      }
    }
    that.setData({
      vedios: vedio,
      tasks: tasks,
      playStatus: playStatus
    })
  },

  

  previewPdf: function (e) {
    const downloadTask = wx.downloadFile({
      url: e.currentTarget.dataset.pdf, //仅为示例，并非真实的资源
      success: function (res) {
        console.log(res);
        var filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function(res) {
            console.log(res)
          }
        })
      }
    })

    downloadTask.onProgressUpdate((res) => {
      wx.showLoading({
        title: '加载中...' + res.progress + '%',
      })
      if (res.progress === 100) {
        wx.hideLoading()
      }
    })
  },

  onPlaying: function (e) {
    this.setData({
      currentVideoId: e.currentTarget.id
    })
    this.videoContext = wx.createVideoContext(this.data.currentVideoId)

  },
  

  bindSwitchVideo: function (e) {
    var playStatus = this.data.playStatus

    for(var i in playStatus) {
      playStatus[i] = false;
    }

    playStatus[e.currentTarget.id] = true;
    if (this.data.currentVideoId) {
      this.videoContext.pause();
    }

    this.setData({
      playStatus: playStatus
    })

    this.setData({
      currentVideoId: "myVideo" + e.currentTarget.id
    })
    this.videoContext = wx.createVideoContext(this.data.currentVideoId)
    this.videoContext.play()
  }
});
